<template>
  <div>
    <home-header :categories="categories" @change="change"></home-header>
    <div class="home-slide">
      <cube-slide :data="slides" />
    </div>
    <h2 class="home-title">课程列表</h2>
    <div class="home-list">
      <cube-recycle-list
        class="list"
        :size="size"
        :on-fetch="onFetch"
        :offset="offset"
        ref='list'
      >
        <template slot="item" slot-scope="{ data }">
          <div :id="data.id" class="item">
              <!-- <h2>{{data.title}}</h2> -->
              <img :src="data.pic" alt="" srcset="">
              <!-- <p>{{data.price}}</p> -->
          </div>
        </template>
      </cube-recycle-list>
    </div>
  </div>
</template>

<script>
import HomeHeader from "./HomeHeader";
//import { mapState, mapActions } from "vuex"; 写法二
import { createNamespacedHelpers } from "vuex";
import { fetchLessonList } from "@/api/home.js";
let { mapState, mapActions,mapMutations } = createNamespacedHelpers("home");
export default {
  data() {
    return {
      size: 5,
      offset: 100,
      offsetIndex: 0,
      hasMore: true,
    };
  },
  //一开始这里的computed被下面的computed覆盖了...
  // mapState和mapGetters放在computed里面
  computed: {
    ...mapState(["categories", "slides"]),
    // ...mapState("home", ["categories"]),  写法二
  },
  components: {
    HomeHeader,
  },
  //mapActions跟mapMutations都放在methods里面
  methods: {
    async onFetch() {
      if (this.hasMore) {
        let { hasMore, result } = await fetchLessonList(
          this.size,
          this.offsetIndex
        );
        this.hasMore = hasMore;
        this.offsetIndex = this.offsetIndex + result.length;
        return result;
      } else {
        return false;
      }
    },
    //根据事件的方法，数据从子传到父
    change(value) {
      this.setCurrentLesson(value);
      this.hasMore = true
      this.offsetIndex = 0
      this.$refs.list.reset()
    },
    ...mapMutations(['setCurrentLesson']),
    ...mapActions(["setCategories", "setSlides"]),
    //  ...mapActions('home',['setCategories']) //返回的是一个函数 setCategories  写法二
  },
  create() {},
  mounted() {
    this.setCategories();
    this.setSlides();
    // this.$store.dispatch("home/setCategories");
  },
};
</script>
<style lang="less">
// .home-slide {
//   width: 100%;
//   height: 150px;
//   img{
//     width: 100%;
//     height: 150px;
//   }
// }
.home {
  &-slide {
    width: 100%;
    height: 150px;
  }
  &-title {
    line-height: 35px;
    font-weight: bold;
    padding-left: 20px;
  }
}
  img {
    width: 100%;
    height: 150px;
  }
  .item{
    margin-top: 20px;
  }
</style>
